package com.nongcai159.mall.lib_common.widgets

import android.content.Context
import android.support.v4.view.ViewPager
import android.util.AttributeSet
import android.view.MotionEvent

/**
 * Created by tanbiheng on 2017/10/13.
 */

class DefViewPager : ViewPager {

    private var fixGesture = false
    private var downX = 0f
    private var downY = 0f

    constructor(context: Context) : super(context) {
        init()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init()
    }

    private fun init() {

    }

    fun setFixGesture(fixGesture: Boolean) {
        this.fixGesture = fixGesture
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (fixGesture) {
            when (ev.action) {
                MotionEvent.ACTION_DOWN -> {
                    downY = ev.y
                    downX = ev.x
                    parent.requestDisallowInterceptTouchEvent(true)
                }
                MotionEvent.ACTION_MOVE -> if (Math.abs(ev.x - downX) > Math.abs(ev.y - downY)) {
                    parent.requestDisallowInterceptTouchEvent(true)
                } else {
                    parent.requestDisallowInterceptTouchEvent(false)
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    downX = 0f
                    downY = 0f
                    parent.requestDisallowInterceptTouchEvent(false)
                }
            }
        }

        return super.dispatchTouchEvent(ev)
    }
}
